package com.iwithlong.controller;

import com.imesne.assistant.common.runtime.RunBinder;
import com.iwithlong.context.Constants;
import com.iwithlong.context.ResultConst;
import com.iwithlong.entity.Member;
import com.iwithlong.service.MemberService;
import com.iwithlong.service.SmsService;
import com.iwithlong.utils.SessionUtil;
import com.iwithlong.vo.MemberVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * User : liulu
 * Date : 2017/6/19 20:53
 * version $Id: SmsController.java, v 0.1 Exp $
 */
@Controller
public class SmsController {

    @Resource
    private SmsService smsService;

    @Resource
    private MemberService memberService;


    /**
     * 发送短信
     * @param mobile
     * @param session
     * @return
     */
    @RequestMapping("/verification/code.json")
    public String sendVerificationCode (String mobile, HttpSession session,Model model) {

        String code = smsService.sendVerificationCode( mobile);
        session.setAttribute(Constants.VERIFICATION_CODE, code);
        if(RunBinder.hasErrors()){
            model.addAttribute(ResultConst.SUCCESS,false);
            model.addAttribute(ResultConst.MESSAGE,RunBinder.getStrErrors());
            return "";
        }

        return "";
    }

    /**
     * 验证 验证码
     * @param verificationCode
     * @param mobile
     * @param session
     * @return
     */
    @PostMapping("/validate/code.json")
    public String validateCode (String verificationCode, String mobile ,HttpSession session,Model model) {

        smsService.validateCode(session, verificationCode);
        MemberVo loginMember = SessionUtil.getSessionMember(session);
        Member member = memberService.get (loginMember.getMemberId ());

        if(RunBinder.hasErrors()){
            model.addAttribute(ResultConst.SUCCESS,false);
            model.addAttribute(ResultConst.MESSAGE,RunBinder.getStrErrors());
            return "";
        }

        if (StringUtils.isEmpty (member.getMobile ())) {
            loginMember.setMobile (mobile);
            memberService.updateMember (loginMember);
            model.addAttribute(ResultConst.SUCCESS,true);
            model.addAttribute(ResultConst.MESSAGE, "绑定手机成功");
        }else if (!StringUtils.equals (mobile,loginMember.getMobile ())) {
            model.addAttribute(ResultConst.SUCCESS,false);
            model.addAttribute(ResultConst.MESSAGE, "该帐号已绑定手机");
        }else {
            model.addAttribute(ResultConst.SUCCESS,true);
            model.addAttribute(ResultConst.MESSAGE, "手机验证通过");
        }

        return "";
    }


}
